package com.rtsapp.server.benchmark.runner.channel;

/**
 * Created by admin on 16-6-18.
 */

import com.rtsapp.server.benchmark.ITestCaseIterator;
import com.rtsapp.server.benchmark.cases.cmd.CommandCaseHandler;
import com.rtsapp.server.benchmark.runner.ICommandCaseHandlerFactory;
import com.rtsapp.server.logger.Logger;
import com.rtsapp.server.logger.LoggerFactory;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

import java.util.Map;

/**
 * ChannelInitializer
 */
public class CommandCaseChannelInitializer extends ChannelInitializer<SocketChannel> {

    private static final Logger LOG = LoggerFactory.getLogger( CommandCaseChannelInitializer.class  );


    private final ICommandCaseHandlerFactory commandCaseHandlerFactory;
    private final EventLoopGroup eventLoop;
    private final ITestCaseIterator iterator;
    private final Map<String,Object> contxt;

    public CommandCaseChannelInitializer(ICommandCaseHandlerFactory commandCaseHandlerFactory, EventLoopGroup eventLoop, ITestCaseIterator iterator, Map<String, Object> contxt) {
        this.commandCaseHandlerFactory = commandCaseHandlerFactory;
        this.eventLoop = eventLoop;
        this.iterator = iterator;
        this.contxt = contxt;
    }

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {

        ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(40960, 0, 4));

        // 初始化设置caseHandler: 事件循环, 用例迭代器, 测试上下文
        CommandCaseHandler caseHandler =  commandCaseHandlerFactory.createCommandHandler();
        caseHandler.initialize(eventLoop, iterator, contxt);
        ch.pipeline().addLast(caseHandler);

        CommandTestOutHandler outHander = new CommandTestOutHandler(caseHandler);
        ch.pipeline().addLast(outHander);

    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

        LOG.error("CommandCaseChannelInitializer exceptionCaught ", cause);
        super.exceptionCaught( ctx, cause );
    }
}